package qwq.zyu.Scoreboard;

import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.Set;

public class qwqOneshotScoreboardWriter implements CommandExecutor {

    private final Plugin plugin;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");

    public qwqOneshotScoreboardWriter(Plugin plugin) {
        this.plugin = plugin;
    }

    @Override
    public boolean onCommand(
            CommandSender sender,
            Command command,
            String label,
            String[] args
    ){
        sender.sendMessage("[qwq_spigot_plugin] debug: args[] = " + Arrays.toString(args));
        sender.sendMessage("[qwq_spigot_plugin] command.getName(): ", command.getName());

        if ( args.length != 1 ){
            sender.sendMessage("[qwq_spigot_plugin] [debug] args.length != 1, return false ");
            return false;
        }

        String scoreboardName = args[0];
        sender.sendMessage("[qwq_spigot_plugin] debug: args[0] = " + args[0]);

        ScoreboardManager manager = Bukkit.getScoreboardManager();
        Scoreboard mainScoreboard = manager.getMainScoreboard();

        Objective obj = mainScoreboard.getObjective(scoreboardName);
        if ( obj==null ){
            sender.sendMessage("[qwq_spigot_plugin]Scoreboard not found");
            return false;
        }

        Set<String> entries = obj.getScoreboard().getEntries();
        StringBuilder outputSb = new StringBuilder();
//        for ( String entry: entries ){
//            Score score = obj.getScore(entry);
//            outputSb.append(entry).append(": ").append(score.getScore()).append("\n");
//            sender.sendMessage(entry + ": " + score.getScore());
//        }
        for (String entry : entries) {
            // 忽略以#开头的特殊标记条目
            if (entry.startsWith("#")) continue;

            // 尝试获取玩家对象
            OfflinePlayer player = Bukkit.getOfflinePlayer(entry);

            // 如果玩家存在并且不是匿名玩家（即UUID格式），则认为这是有效的玩家条目
            if (!Objects.equals(player.getName(), entry)) { // 检查是否为玩家名称而不是UUID
                continue;
            }

            Score score = obj.getScore(entry);
            outputSb.append(player.getName()).append(": ").append(score.getScore()).append("\n");
            sender.sendMessage(player.getName() + ": " + score.getScore());
        }

        try{
            writeToFile(outputSb.toString(), scoreboardName);
            sender.sendMessage("Scoreboard has been saved to file.");
        } catch (Exception e){
            sender.sendMessage("Failed to save scoreboard to file.");
            e.printStackTrace();
        }

        return true;

    }

//    private void writeToFile(String content, String scoreboardName) throws IOException {
//        String timestamp = dateFormat.format(new Date());
//        String filename = "scoreboard_" + scoreboardName + "_" + timestamp + ".txt";
//        try (FileWriter writer = new FileWriter(filename)) {
//            writer.write(content);
//        }
//    }

    private void writeToFile(String content, String scoreboardName) throws IOException {
        // 获取插件数据文件夹
        File dataFolder = plugin.getDataFolder();
        // 创建插件名同名文件夹下的 scoreboard 文件夹
        File scoreboardDir = new File(dataFolder, "scoreboard_data");
        if (!scoreboardDir.exists()) {
            scoreboardDir.mkdirs(); // 如果不存在则创建目录
        }

        String timestamp = dateFormat.format(new Date());
//        String filename = "scoreboard_" + scoreboardName + "_" + timestamp + ".txt";
        String filename = "scoreboard_" + scoreboardName + ".txt";
        File file = new File(scoreboardDir, filename);

        try (FileWriter writer = new FileWriter(file)) {
            writer.write(content);
        }
    }



}
